package com.btex.app.treaty;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.btex.app.Config;
import com.btex.app.FuturesKLineActivity;
import com.btex.app.LoginActivity;
import com.btex.app.MyApplication;
import com.btex.app.R;
import com.btex.app.WebActivity;
import com.btex.app.entity.CostInfo;
import com.btex.app.entity.FuturesInfo;
import com.btex.app.entity.FuturesListInfo;
import com.btex.app.entity.HeYueEventBusInfo;
import com.btex.app.entity.MyFuturesInfo;
import com.btex.app.entity.TreatyDishListInfo;
import com.btex.app.entity.TreatyEntrustInfo;
import com.btex.app.entity.UnwindInfo;
import com.btex.app.pager.BaseFragment;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.DensityUtil;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Tools;
import com.btex.app.tools.Util;
import com.btex.app.treaty.dialog.CheckPriceDialog;
import com.btex.app.treaty.dialog.EarnestDialog;
import com.btex.app.treaty.dialog.LeverSetDialog;
import com.btex.app.treaty.dialog.MoShiDialog;
import com.btex.app.treaty.dialog.TreatySetDialog;
import com.btex.app.treaty.dialog.UnitsDialog;
import com.btex.app.treaty.dialog.UnwindDialog;
import com.btex.app.treaty.list.EntrustListAdapter;
import com.btex.app.treaty.list.EntrustListbuyAdapter;
import com.btex.app.treaty.list.EntrustListsellAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.text.InputType.TYPE_CLASS_NUMBER;
import static android.text.InputType.TYPE_NUMBER_FLAG_DECIMAL;
import static android.text.InputType.TYPE_NUMBER_VARIATION_NORMAL;
import static com.btex.app.R.string.num;

/**
 * @author zy zhangyi <zhangyi, 1104745049@QQ.com
 * @version v1.0
 * @project study1
 * @Description
 * @encoding UTF-8
 * @date 2018/10/15
 * @time 上午10:56
 * @修改记录 <pre>
 * 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 * </pre>
 */

public class TreatyFragment extends BaseFragment {
    Unbinder unbinder;
    @BindView(R.id.treaty_recy)
    RecyclerView mTreatyRecy;
    @BindView(R.id.treaty_recy_sell)
    RecyclerView mTreatyRecySell;
    @BindView(R.id.treaty_recy_buy)
    RecyclerView mTreatyRecyBuy;
    @BindView(R.id.treaty_jisuan)
    ImageView mTreatyJisuan;
    @BindView(R.id.treaty_more)
    ImageView mTreatyMore;
    @BindView(R.id.treaty_behavior_tv_history)
    TextView mTreatyBehaviorTvHistory;
    @BindView(R.id.treaty_tv_history)
    TextView mTreatyTvHistory;
    @BindView(R.id.treaty_behavior_tv_current_history)
    TextView mTreatyBehaviorTvCurrentHistory;
    @BindView(R.id.include_positions)
    LinearLayout mIncludePositions;
    @BindView(R.id.treary_check_price_lin)
    LinearLayout mTrearyCheckPriceLin;
    @BindView(R.id.treary_check_price_tv)
    TextView mTrearyCheckPriceTv;
    @BindView(R.id.treary_lever_tv)
    TextView mTrearyLeverTv;
    @BindView(R.id.treary_lever_lin)
    LinearLayout mTrearyLeverLin;
    @BindView(R.id.treaty_behavior_ed_number)
    EditText mTreatyBehaviorEdNumber;
    @BindView(R.id.treaty_behavior_tv_number)
    TextView mTreatyBehaviorTvNumber;
    @BindView(R.id.treaty_behavior_ed_price)
    EditText mTreatyBehaviorEdPrice;
    @BindView(R.id.treaty_behavior_tv_price)
    TextView mTreatyBehaviorTvPrice;
    @BindView(R.id.treaty_behavior_but_long)
    Button mTreatyBehaviorButLong;
    @BindView(R.id.treaty_behavior_tv_long_price)
    TextView mTreatyBehaviorTvLongPrice;
    @BindView(R.id.treaty_behavior_but_short)
    Button mTreatyBehaviorButShort;
    @BindView(R.id.treaty_behavior_but_short_price)
    TextView mTreatyBehaviorButShortPrice;
    @BindView(R.id.treaty_behavior_tv_entrust_value)
    TextView mTreatyBehaviorTvEntrustValue;
    @BindView(R.id.treaty_behavior_tv_remaining_balance)
    TextView mTreatyBehaviorTvRemainingBalance;
    @BindView(R.id.treaty_behavior_tv_change)
    TextView mTreatyBehaviorTvChange;
    @BindView(R.id.treary_check_danwei_lin)
    LinearLayout mTrearyCheckDanweiLin;
    @BindView(R.id.include_empty_positions)
    LinearLayout mIncludeEmptyPositions;
    @BindView(R.id.treary_check_tv_kine)
    TextView mTrearyCheckTvKine;
    @BindView(R.id.treaty_positions_tv_name)
    TextView mTreatyPositionsTvName;
    @BindView(R.id.treaty_positions_tv_open_price)
    TextView mTreatyPositionsTvOpenPrice;
    @BindView(R.id.treaty_positions_tv_Strong_price)
    TextView mTreatyPositionsTvStrongPrice;
    @BindView(R.id.treaty_positions_tv_Unrealized_money)
    TextView mTreatyPositionsTvUnrealizedMoney;
    @BindView(R.id.treaty_positions_tv_realized_money)
    TextView mTreatyPositionsTvRealizedMoney;
    @BindView(R.id.treaty_positions_tv_holdings)
    TextView mTreatyPositionsTvHoldings;
    @BindView(R.id.treaty_positions_tv_position_value)
    TextView mTreatyPositionsTvPositionValue;
    @BindView(R.id.treaty_positions_tv_margin)
    TextView mTreatyPositionsTvMargin;
    @BindView(R.id.treaty_positions_lin_tiaozheng)
    LinearLayout mTreatyPositionsLinTiaozheng;
    @BindView(R.id.treaty_positions_lin_ping)
    LinearLayout mTreatyPositionsLinPing;
    @BindView(R.id.treaty_tv_index_price)
    TextView mTreatyTvIndexPrice;
    @BindView(R.id.treaty_tv_new_index)
    TextView mTreatyTvNewIndex;
    @BindView(R.id.treaty_positions_view)
    View mTreatyPositionsView;
    @BindView(R.id.treaty_positions_tv_name_type)
    TextView mTreatyPositionsTvNameType;
    @BindView(R.id.treary_name_type)
    TextView mTrearyNameType;
    //    @BindView(R.id.treaty_recy_history)
//    RecyclerView mTreatyRecyHistory;
    @BindView(R.id.treaty_behavior_ed_rela_price)
    RelativeLayout mTreatyBehaviorEdRelaPrice;
    @BindView(R.id.treary_check_danwei_tv)
    TextView treary_check_danwei_tv;
    @BindView(R.id.treaty_positions_tv_ganggan)
    TextView treaty_positions_tv_ganggan;
    @BindView(R.id.treaty_positions_ganggan)
    TextView mTreatyPositionsGanggan;
    @BindView(R.id.treaty_tv_heli_price)
    TextView mTreatyTvHeliPrice;
    @BindView(R.id.treaty_tv_history_lin)
    LinearLayout mTreatyTvHistoryLin;
    @BindView(R.id.treaty_behavior_tv_current_history_lin)
    LinearLayout mTreatyBehaviorTvCurrentHistoryLin;
    @BindView(R.id.treaty_behavior_tv_history_lin)
    LinearLayout mTreatyBehaviorTvHistoryLin;
    @BindView(R.id.treaty_behavior_ed_lin_price)
    LinearLayout treaty_behavior_ed_lin_price;
    @BindView(R.id.treary_name_type_lin)
    LinearLayout treary_name_type_lin;

    @BindView(R.id.treaty_behavior_lin_number)
    LinearLayout treaty_behavior_lin_number;
    @BindView(R.id.treary_lever_shuliang_type)
    TextView mTrearyLeverShuliangType;

    @BindView(R.id.treary_name_jisuan)
    TextView treary_name_jisuan;
    @BindView(R.id.treary_but_zhang)
    Button mTrearyButZhang;
    @BindView(R.id.treary_but_btc)
    Button mTrearyButBtc;
    @BindView(R.id.treaty_tv_jiage)
    TextView mTreatyTvJiage;
    @BindView(R.id.heyue_wei_shixian)
    TextView mHeyueWeiShixian;
    @BindView(R.id.heyue_yi_shixian)
    TextView mHeyueYiShixian;

    //    treary_check_danwei_tv
    //    合约数量
    private double mTreatyNumber = 0.0;
    //    合约单价
    private double mTreatyPrice = 0.0;
    private EntrustListAdapter mEntrustListAdapter;
    private EntrustListsellAdapter mEntrustListsellAdapter;
    private EntrustListbuyAdapter mEntrustListbuyAdapter;
    private MicroAVLIDialog mMicroAVLIDialog;
    public String refreshType = "1";
    private List<UnwindInfo.DataBean.PositionListsBean> mPosition_lists;
    private boolean mIsVisibleToUser;
    private UnwindInfo mUnwindInfo;
    //    状态切换
    public String isLimit = "";
    public String isZhang = "1";
    public String valuation = "BTC";
    private FuturesInfo mFuturesInfo;
    private RecyclerView mPop_treaty_recy_list;
    private PopTreatyAdapter mPopTreatyAdapter;
    //    所有期货列表
    private FuturesListInfo mFuturesListInfo;
    private String mIsreverse = "1";
    private OrderHisInfoAdapter mOrderHisInfoAdapter;
    private String mPair = "BTC_USD";
    //    private String lever = "";
    private String changeType = "1";
    private String leverage = "";
    private ArrayList<String> mStrings;
    //    仓位杠杆
    private String mLeverage = "";
    //    仓位id
    private String mContract_id;
    private String mPrice_float_num = "2";
    private String mSa_float_num = "8";
    private String mIs_cross;
    private String mNumber;
    private String mPrice;
    private String mSettle_anchor = "";
    private String mMax_leverage;
    private String mAllow_cross = "";
    private String mContract_anchor;
    private String mQuote_anchor;
    private String mCang_yu_e;
    //    刷新状态
    private boolean isWeiTuo = true;
    private boolean isPositions = true;
    private boolean isOrders = true;
    private boolean isCcontracts = true;
    private boolean isFuturesInfo = true;
    private boolean isInfo = true;
    public double oldPrice = 0;
    private String mContract_value = "1";
    public boolean isOncilk = false;

    private int beforeDot = 8;
    private int afterDot = 8;

    public boolean isShow = true;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.treaty_fragment, null);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mMicroAVLIDialog = new MicroAVLIDialog(getActivity());
        initRecy();

        EventBus.getDefault().register(this);
        if (mTrearyButZhang != null) {
            mTrearyButZhang.setSelected(true);
        }

        if (mTreatyBehaviorTvLongPrice != null) {
            mTreatyBehaviorTvLongPrice.setText(getString(R.string.heyue_chengben) + "\t" + "0.00");
        }

        if (mTreatyBehaviorButShortPrice != null) {
            mTreatyBehaviorButShortPrice.setText(getString(R.string.heyue_chengben) + "\t" + "0.00");
        }
        if (mTrearyLeverShuliangType != null) {
            mTrearyLeverShuliangType.setText(getString(num) + "(" + getString(R.string.zhang) + ")");
        }
        if (mTreatyTvHistory != null) {
            mTreatyTvHistory.setSelected(true);
        }


        getMxCcontracts(refreshType);
        getInfo();
//        getListInfo(refreshType);
        getMyPositions(refreshType);
//        当前委托
        getMyOrders(refreshType);
        getFuturesInfo();
//        get_my_orders_his(refreshType);
        initStatPositions();
        initOnclikListener();


    }

    private void getMxCcontracts(String type) {

        isCcontracts = false;

        int num = (int) ((Math.random() * 9 + 1) * 100000);


        OkGo.<String>get(Config.GET_MX_CONTRACTS + "?rnd=" + String.valueOf(num)).params("contract_id", type).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body().toString();
                isCcontracts = true;
                Log.i("mgfubvjsjhdjshdsjhdygu", result);

                try {

                    JSONObject jsonObj = new JSONObject(result);
                    if (jsonObj.getString("code").equals("1")) {
                        String data = jsonObj.getString("data");
                        if (!data.equals("null")) {
                            setMxCcontracts(result);
                            getListInfo(refreshType);
                        }

                    } else {

                    }

                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }
        });


//        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
//        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
//        RequestParams params = new RequestParams();
//        params.addHeader("app-version", Config.VERSION);
//        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
//        params.addHeader("my-client", "android");
//        params.addQueryStringParameter("contract_id", type);

//        MyApplication.get().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_MX_CONTRACTS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                isCcontracts = true;
//                Log.i("mgfubvjsjhdjshdsjhdygu", responseInfo.result);
//
//                try {
//
//                    JSONObject jsonObj = new JSONObject(responseInfo.result);
//                    if (jsonObj.getString("code").equals("1")) {
//                        String data = jsonObj.getString("data");
//                        if (!data.equals("null")) {
//                            setMxCcontracts(responseInfo.result);
//                            getListInfo(refreshType);
//                        }
//
//                    } else {
//
//                    }
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//            }
//
//        });

    }

    private void setMxCcontracts(String result) {

        Gson gson = new Gson();
        mFuturesInfo = gson.fromJson(result, FuturesInfo.class);
        mContract_value = mFuturesInfo.getData().getContract_value();
        mSettle_anchor = mFuturesInfo.getData().getSettle_anchor();
        mQuote_anchor = mFuturesInfo.getData().getQuote_anchor();
        mSa_float_num = mFuturesInfo.getData().getSa_float_num();
        mPrice_float_num = mFuturesInfo.getData().getPrice_float_num();
        mMax_leverage = mFuturesInfo.getData().getMax_leverage();
        mAllow_cross = mFuturesInfo.getData().getAllow_cross();
        mContract_anchor = mFuturesInfo.getData().getContract_anchor();
        String pair = mFuturesInfo.getData().getPair();
        String contract_anchor = mFuturesInfo.getData().getContract_anchor();
        mTreatyTvJiage.setText(getString(R.string.k_price) + "(" + mQuote_anchor + ")");
        mPair = pair;

        mTrearyNameType.setText(mPair + "\t" + getString(R.string.yongxu));
        treary_name_jisuan.setText("(" + mSettle_anchor + getString(R.string.jiesuan) + ")");

        if (!mAllow_cross.equals("1")) {
            treary_check_danwei_tv.setText(getString(R.string.zhucang));
        }

//        beforeDot = Integer.valueOf(mSa_float_num);
//        afterDot = Integer.valueOf(mPrice_float_num);
//        设置输入框小数点之后数量
//        if (!TextUtils.isEmpty(mSa_float_num) && !TextUtils.isEmpty(mPrice_float_num)) {
//            mTreatyBehaviorEdNumber.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(Integer.valueOf(mSa_float_num))});
//            mTreatyBehaviorEdPrice.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(Integer.valueOf(mPrice_float_num))});
//        }

        double trade_price = mFuturesInfo.getData().getTicker().getTrade_price();
        double change_24h = mFuturesInfo.getData().getTicker().getChange_24h();
        if (oldPrice > trade_price) {
            mTreatyTvIndexPrice.setTextColor(getResources().getColor(R.color.red));
            mTreatyTvIndexPrice.setCompoundDrawablesWithIntrinsicBounds(null,
                    null, getActivity().getResources().getDrawable(R.mipmap.futures_xia), null);
            mTreatyTvIndexPrice.setCompoundDrawablePadding(1);

        } else if (oldPrice == trade_price) {

        } else {
            mTreatyTvIndexPrice.setCompoundDrawablesWithIntrinsicBounds(null,
                    null, getActivity().getResources().getDrawable(R.mipmap.futures_shang), null);
            mTreatyTvIndexPrice.setCompoundDrawablePadding(1);
            mTreatyTvIndexPrice.setTextColor(Color.parseColor("#73a41d"));
        }
        oldPrice = trade_price;

        mIsreverse = mFuturesInfo.getData().getIsreverse();


        mTreatyTvIndexPrice.setText(String.valueOf(Tools.round(trade_price, Integer.valueOf(mPrice_float_num))));
        mTreatyTvNewIndex.setText(getString(R.string.zhishu) + "\t" + Tools.round(Double.valueOf(mFuturesInfo.getData().getTicker().getIndex_price()), Integer.valueOf(mPrice_float_num)).toString());
        mTreatyTvHeliPrice.setText(getString(R.string.gongpingprice) + "\t" + Tools.round(Double.valueOf(mFuturesInfo.getData().getTicker().getMark_price()), Integer.valueOf(mPrice_float_num)).toString());

//        设置杠杆率start
        String leverage_steps = mFuturesInfo.getData().getLeverage_steps();
        String[] leverages = leverage_steps.split(",");

        mStrings = new ArrayList<>();
        for (int i = 0; i < leverages.length; i++) {
            mStrings.add(leverages[i]);
        }

        if (TextUtils.isEmpty(mLeverage)) {

            try {

                int size = mStrings.size();
                double floor = Math.floor(size / 2);
                mLeverage = mStrings.get((int) floor);
                Log.i("wkehfiwuheifuwhief", mLeverage);
                mTrearyLeverTv.setText(mLeverage + "X");

            } catch (Exception e) {

            }

        }

    }
//        设置杠杆率end


    private void getMyPositions(String Positions) {

        isPositions = false;
        int num = (int) ((Math.random() * 9 + 1) * 100000);


        OkGo.<String>get(Config.GET_MY_POSITIONS + "?rnd=" + String.valueOf(num)).params("contract_id", Positions).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body().toString();
                isPositions = true;
                Log.i("bcnxbctweiauiwe", result);

                try {

                    JSONObject jsonObj = new JSONObject(result);
                    if (jsonObj.getString("code").equals("1")) {
                        setUnwind(result);
                    } else {

                        if (mTreatyBehaviorTvCurrentHistory != null || mTreatyBehaviorTvHistory != null) {
                            if (mTreatyBehaviorTvCurrentHistory.isSelected() | mTreatyBehaviorTvHistory.isSelected()) {

                            } else {
                                SetStat();
                                if (mIncludeEmptyPositions != null) {
                                    mIncludeEmptyPositions.setVisibility(View.VISIBLE);
                                }
                            }
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

//        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
//        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
//        RequestParams params = new RequestParams();
//        params.addHeader("app-version", Config.VERSION);
//        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
//        params.addHeader("my-client", "android");
//        params.addQueryStringParameter("contract_id", Positions);
//
//        MyApplication.get().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_MY_POSITIONS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                isPositions = true;
//                Log.i("bcnxbctweiauiwe", responseInfo.result);
//
//                try {
//
//                    JSONObject jsonObj = new JSONObject(responseInfo.result);
//                    if (jsonObj.getString("code").equals("1")) {
//                        setUnwind(responseInfo.result);
//                    } else {
//
//                        if (mTreatyBehaviorTvCurrentHistory != null || mTreatyBehaviorTvHistory != null) {
//                            if (mTreatyBehaviorTvCurrentHistory.isSelected() | mTreatyBehaviorTvHistory.isSelected()) {
//
//                            } else {
//                                SetStat();
//                                if (mIncludeEmptyPositions != null) {
//                                    mIncludeEmptyPositions.setVisibility(View.VISIBLE);
//                                }
//
//                            }
//                        }
//
//
//                    }
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//            }
//
//        });
    }

    private void setUnwind(String result) {

        Gson gson = new Gson();
        mUnwindInfo = gson.fromJson(result, UnwindInfo.class);
        mPosition_lists = mUnwindInfo.getData().getPosition_lists();

        boolean selected = mTreatyBehaviorTvCurrentHistory.isSelected();
        boolean selected1 = mTreatyBehaviorTvHistory.isSelected();
        if (selected || selected1) {

        } else {

            if (mPosition_lists.size() > 0) {
                Log.i("WKEFWEFHIWHEIFIUWEH", "1");


                String amount = mPosition_lists.get(0).getAmount();
                if (amount.equals("0")) {
                    isOncilk = false;
                    SetStat();
                    if (mIncludeEmptyPositions != null) {
                        mIncludeEmptyPositions.setVisibility(View.VISIBLE);
                    }


                } else {
                    isOncilk = true;
                    SetStat();

                    if (mIncludePositions != null) {
                        mIncludePositions.setVisibility(View.VISIBLE);
                    }


                    try {

                        setUnwindInfo(mPosition_lists);

                    } catch (Exception e) {

                    }

                }

            } else {
                Log.i("WKEFWEFHIWHEIFIUWEH", "2");
                isOncilk = false;
                SetStat();
                if (mIncludeEmptyPositions != null) {
                    mIncludeEmptyPositions.setVisibility(View.VISIBLE);
                }

            }
        }

    }

    private void setUnwindInfo(List<UnwindInfo.DataBean.PositionListsBean> position_lists) {

        UnwindInfo.DataBean.PositionListsBean positionListsBean = position_lists.get(0);
        mTreatyPositionsTvName.setText(positionListsBean.getSymbol());
        String margin = positionListsBean.getMargin();
        String delta_margin = positionListsBean.getDelta_margin();
        Double Doublemargin = Double.valueOf(margin);
        Double Doubledeltamargin = Double.valueOf(delta_margin);
        double v2 = Doublemargin + Doubledeltamargin;
        String s = String.valueOf(v2);

//       是否全仓
        mIs_cross = positionListsBean.getIs_cross();


//        开仓价
        if (!TextUtils.isEmpty(mPrice_float_num)) {
            String openPrice = Tools.round(Double.valueOf(positionListsBean.getPrice()), Integer.valueOf(mPrice_float_num)).toString();
            mTreatyPositionsTvOpenPrice.setText(openPrice);
        } else {
            mTreatyPositionsTvOpenPrice.setText(positionListsBean.getPrice());
        }

//        强平价格
        if (!TextUtils.isEmpty(mPrice_float_num)) {

            String qiangpingPrice = Tools.round(Double.valueOf(positionListsBean.getLiquidation_price()), Integer.valueOf(mPrice_float_num)).toString();
            mTreatyPositionsTvStrongPrice.setText(qiangpingPrice);
        } else {
            mTreatyPositionsTvStrongPrice.setText(positionListsBean.getLiquidation_price());
        }

//        仓位保证金
        if (!TextUtils.isEmpty(mSa_float_num)) {
            String trim1 = Tools.round(Double.valueOf(s), Integer.valueOf(mSa_float_num)).toString().trim();
            mTreatyPositionsTvMargin.setText(trim1 + "\t" + positionListsBean.getSettle_anchor());
        } else {
            String trim1 = Tools.round(Double.valueOf(s), 8).toString().trim();
            mTreatyPositionsTvMargin.setText(trim1 + "\t" + positionListsBean.getSettle_anchor());
        }

//        已实现盈亏
        if (!TextUtils.isEmpty(mSa_float_num)) {
            String trim = Tools.round(Double.valueOf(positionListsBean.getRlz_pnl()), Integer.valueOf(mSa_float_num)).toString().trim();
            BigDecimal db2 = new BigDecimal(trim);
            String yishixian = db2.toPlainString();
//            mTreatyPositionsTvRealizedMoney.setText(yishixian + "\t" + positionListsBean.getSettle_anchor());
            mTreatyPositionsTvRealizedMoney.setText(yishixian);
            mHeyueYiShixian.setText(getString(R.string.heyue_yi_shixian) + "(" + positionListsBean.getSettle_anchor() + ")");
        } else {
//            mTreatyPositionsTvRealizedMoney.setText(positionListsBean.getRlz_pnl() + "\t" + positionListsBean.getSettle_anchor());
            mTreatyPositionsTvRealizedMoney.setText(positionListsBean.getRlz_pnl());
            mHeyueYiShixian.setText(getString(R.string.heyue_yi_shixian) + "(" + positionListsBean.getSettle_anchor() + ")");
        }

        String rlz_pnl = positionListsBean.getRlz_pnl();

        Double aDouble = Double.valueOf(rlz_pnl);
        if (aDouble > 0) {
            mTreatyPositionsTvRealizedMoney.setTextColor(getResources().getColor(R.color.bg_green));
        } else {
            mTreatyPositionsTvRealizedMoney.setTextColor(getResources().getColor(R.color.red));
        }


        String direction = positionListsBean.getDirection();
        if ("1".equals(direction)) {
            mTreatyPositionsTvHoldings.setText(positionListsBean.getAmount());
            mTreatyPositionsTvHoldings.setTextColor(getResources().getColor(R.color.bg_green));
            mTreatyPositionsView.setBackgroundResource(R.color.bg_green);
            mTreatyPositionsTvNameType.setText(getResources().getString(R.string.heyue_duo));
//            mTreatyPositionsTvNameType.setTextColor(getResources().getColor(R.color.bg_green));
        } else {
            mTreatyPositionsTvHoldings.setText(positionListsBean.getAmount());
            mTreatyPositionsTvHoldings.setTextColor(getResources().getColor(R.color.red));
            mTreatyPositionsView.setBackgroundResource(R.color.red);
            mTreatyPositionsTvNameType.setText(getResources().getString(R.string.heyue_kong));
//            mTreatyPositionsTvNameType.setTextColor(getResources().getColor(R.color.red));
        }

        if (mFuturesInfo != null) {

            double v1 = 0;
            double huibao = 0;
            double mark_price = 0;

            int directiontype;
            String direction1 = positionListsBean.getDirection();
            String amount = positionListsBean.getAmount();
            Integer integer = Integer.valueOf(amount);
            String price = positionListsBean.getPrice();
            double v = Double.parseDouble(price);
            mark_price = mFuturesInfo.getData().getTicker().getMark_price();
            String tow_mark_price = Tools.round(mark_price, Integer.valueOf(mPrice_float_num)).toString().trim();
            Double aDouble3 = Double.valueOf(tow_mark_price);
            mark_price = aDouble3;

            mContract_id = positionListsBean.getPosition_id();
            String leverage = positionListsBean.getLeverage();

//            获取仓位杠杆
            mLeverage = positionListsBean.getLeverage();


            String[] split = mLeverage.split("\\.");
            mLeverage = split[0];
            BigDecimal round = Tools.round(Double.valueOf(mLeverage), 2);
            String s1 = round.toString();

            if (mIs_cross.equals("1")) {

//                mTreatyPositionsGanggan.setText(getString(R.string.heyue_quancang));
                mTreatyPositionsGanggan.setText("(" + getString(R.string.heyue_quancang) + "\t" + split[0] + "X" + ")");
//                mTrearyLeverTv.setText(getString(R.string.heyue_quancang));
                Log.i("wkjefkwjekfwkef", "1");
                mTrearyLeverTv.setText(split[0] + "X");
//                treary_check_danwei_tv.setText("全仓");
                treary_check_danwei_tv.setText(getString(R.string.heyue_quancang));

            } else {

                if (s1.contains("-")) {

                    mTreatyPositionsGanggan.setText(getString(R.string.heyue_quancang));
                    mTrearyLeverTv.setText(getString(R.string.heyue_quancang));
                } else {
                    treary_check_danwei_tv.setText(getString(R.string.zhucang));
                    mTreatyPositionsGanggan.setText("(" + getString(R.string.zhucang) + "\t" + split[0] + "X" + ")");
                    Log.i("wkjefkwjekfwkef", "2");
                    mTrearyLeverTv.setText(split[0] + "X");
                }
            }

            String is_reverse = positionListsBean.getIs_reverse();

            if ("-1".equals(positionListsBean.getIs_reverse())) {
                Log.i("wefhowiheofwhe", "1111111111111");

//              正向
                if (direction1.equals("1")) {


                    if (mIs_cross.equals("1")) {
                        v1 = (mark_price - v) * integer * 1;
//                          res_num = (mark_price - open_price) * direction * position_num * single_contract_value;

//                        huibao = integer * 1 * (mark_price - v) / (v * mark_price) * Double.valueOf(mContract_value);

//                        huibao = (mark_price - v) / v * Double.valueOf(mLeverage) * Double.valueOf(leverage) * 1;
//                        huibao = (mark_price - v) / v * Double.valueOf(mMax_leverage) * Double.valueOf(leverage) * 1;
                        huibao = (mark_price - v) * 1 * integer * Double.valueOf(mContract_value);


                    } else {
                        v1 = (mark_price - v) * integer * 1;
//                        huibao = (mark_price - v) / v * Double.valueOf(mLeverage) * Double.valueOf(leverage) * 1;
//                        huibao = integer * 1 * (mark_price - v) / (v * mark_price) * Double.valueOf(mContract_value);
                        huibao = (mark_price - v) * 1 * integer * Double.valueOf(mContract_value);
                    }


//                    huibao = (1 - v / mark_price) * 4 * 100 * 1;

                } else {

                    if (mIs_cross.equals("1")) {
                        v1 = (mark_price - v) * integer * -1;
//                        huibao = (mark_price - v) / v * Double.valueOf(mLeverage) * Double.valueOf(leverage) * -1;
//                        huibao = (mark_price - v) / v * Double.valueOf(mMax_leverage) * Double.valueOf(leverage) * -1;
//                        huibao = integer * -1 * (mark_price - v) / (v * mark_price) * Double.valueOf(mContract_value);
                        huibao = (mark_price - v) * -1 * integer * Double.valueOf(mContract_value);

                    } else {
                        v1 = (mark_price - v) * integer * -1;
//                        huibao = (mark_price - v) / v * Double.valueOf(mLeverage) * Double.valueOf(leverage) * -1;
//                        huibao = integer * -1 * (mark_price - v) / (v * mark_price) * Double.valueOf(mContract_value);
                        huibao = (mark_price - v) * -1 * integer * Double.valueOf(mContract_value);
                    }

                }

//                (1-v/mark_price)*杠杆*100%*方向
//                （mark_price-v）/v杠杆*100%*方向
//
            } else {
//               反向
                Log.i("wefhowiheofwhe", "2222222222222");

                if (direction1.equals("1")) {

                    if (mIs_cross.equals("1")) {
                        directiontype = 1;
//                           res_num = (mark_price - open_price) * direction * position_num * single_contract_value;
                        v1 = (1 / v - 1 / mark_price) * integer * directiontype;

//                        huibao = integer * -1 * (mark_price - v) / (v * mark_price) * Double.valueOf(mContract_value);
                        huibao = integer * 1 * (mark_price - v) / (v * mark_price) * Double.valueOf(mContract_value);
//                        huibao = (1 - v / mark_price) * Double.valueOf(mLeverage) * Double.valueOf(leverage) * 1;
//                        huibao = (1 - v / mark_price) * Double.valueOf(mMax_leverage) * Double.valueOf(leverage) * 1;

                    } else {
                        directiontype = 1;
                        v1 = (1 / v - 1 / mark_price) * integer * directiontype;
//                        huibao = (1 - v / mark_price) * Double.valueOf(mLeverage) * Double.valueOf(leverage) * 1;
                        huibao = integer * 1 * (mark_price - v) / (v * mark_price) * Double.valueOf(mContract_value);
                    }


                } else {
//                       res_num = position_num * direction * (mark_price - open_price) /(open_price*mark_price) * single_contract_value;


                    if (mIs_cross.equals("1")) {
                        directiontype = -1;
                        v1 = (1 / v - 1 / mark_price) * integer * directiontype;
//                        huibao = (1 - v / mark_price) * Double.valueOf(mLeverage) * Double.valueOf(leverage) * -1;
//                        huibao = (1 - v / mark_price) * Double.valueOf(mMax_leverage) * Double.valueOf(leverage) * -1;
                        huibao = integer * -1 * (mark_price - v) / (v * mark_price) * Double.valueOf(mContract_value);
//                        huibao = (mark_price - v) * -1 * integer * Double.valueOf(mContract_value);

                    } else {
                        directiontype = -1;
                        v1 = (1 / v - 1 / mark_price) * integer * directiontype;
//                        huibao = (1 - v / mark_price) * Double.valueOf(mLeverage) * Double.valueOf(leverage) * -1;
                        huibao = integer * -1 * (mark_price - v) / (v * mark_price) * Double.valueOf(mContract_value);
                    }


                }

            }

//            未实现盈亏

            if (v1 > 0) {
                mTreatyPositionsTvUnrealizedMoney.setTextColor(getResources().getColor(R.color.bg_green));
            } else {
                mTreatyPositionsTvUnrealizedMoney.setTextColor(getResources().getColor(R.color.red));
            }

            DecimalFormat decimalFormat = new DecimalFormat("#,##0.00000000");//格式化设置
            String format = decimalFormat.format(v1);
            double newHuibaolv = 0;
            //回报率
            if (mSa_float_num != null) {
                String contract_value = mFuturesInfo.getData().getContract_value();

                if (is_reverse.equals("1")) {

                    Log.i("wliejowijeodiwjef", "1");
//                    res = unrl/(position_num/open_price*single_contract_value)*leverage;
                    newHuibaolv = huibao / (integer / v * Double.valueOf(contract_value)) * Double.valueOf(mLeverage);
                } else {
                    Log.i("wliejowijeodiwjef", "2");
//                    res = unrl/(position_num*open_price*single_contract_value)*leverage;
                    newHuibaolv = huibao / (integer * v * Double.valueOf(contract_value)) * Double.valueOf(mLeverage);
                }

                String weishixian = Tools.round(v1 * Double.valueOf(contract_value), Integer.valueOf(mSa_float_num)).toString().trim();
                String round2 = Tools.round(newHuibaolv * 100, 2).toString().trim();
                BigDecimal db2 = new BigDecimal(round2);
                String weishixianhuibao = db2.toPlainString();
//                mTreatyPositionsTvUnrealizedMoney.setText(weishixian + "\t" + valuation + "(" + weishixianhuibao + "%" + ")");
                mTreatyPositionsTvUnrealizedMoney.setText(weishixian + "(" + weishixianhuibao + "%" + ")");
                mHeyueWeiShixian.setText(getString(R.string.heyue_wei_shixian) + "(" + valuation + ")");

//                全仓
                if (mIs_cross.equals("1")) {
                    String newCangwei = Tools.round(Double.valueOf(s), 8).toString().trim();
                    if (Double.valueOf(weishixian) < 0) {

                        if (!TextUtils.isEmpty(mCang_yu_e)) {
                            String trim = Tools.round(Double.valueOf(mCang_yu_e), Integer.valueOf(mSa_float_num)).toString().trim();
                            Double aDouble1 = Double.valueOf(weishixian);
                            Double aDouble2 = Double.valueOf(trim);
                            double v3 = aDouble2 + aDouble1;
                            String trim2 = Tools.round(v3, Integer.valueOf(mSa_float_num)).toString().trim();
                        }

                    } else {
                        String newCangweis = Tools.round(Double.valueOf(s), 8).toString().trim();
                        String weishixians = Tools.round(Double.valueOf(weishixian), 8).toString().trim();
                        String trim = Tools.round(Double.valueOf(newCangweis) + Double.valueOf(weishixians), Integer.valueOf(mSa_float_num)).toString().trim();
                        mTreatyPositionsTvMargin.setText(trim + "\t" + positionListsBean.getSettle_anchor());
                    }


                } else {

                    //        仓位保证金
                    String newCangwei = Tools.round(Double.valueOf(s), 8).toString().trim();
                    String weishixians = Tools.round(Double.valueOf(weishixian), 8).toString().trim();
                    String trim = Tools.round(Double.valueOf(newCangwei) + Double.valueOf(weishixians), Integer.valueOf(mSa_float_num)).toString().trim();
                    mTreatyPositionsTvMargin.setText(trim + "\t" + positionListsBean.getSettle_anchor());
                }

            } else {
                DecimalFormat decalFormat = new DecimalFormat("#,##0.0000");//格式化设置
                String huibaoalue = decalFormat.format(huibao);
                mTreatyPositionsTvUnrealizedMoney.setText(format + "\t" + valuation + "(" + huibaoalue + "%" + ")");
            }

//               仓位价值

            if ("-1".equals(positionListsBean.getIs_reverse())) {

//                Double wew = mark_price * integer;
//                DecimalFormat decFormat = new DecimalFormat("#,##0.0000");//格式化设置
//                String formt = decimalFormat.format(wew);
//                mTreatyPositionsTvPositionValue.setText(formt + "\t" + valuation);

                if (!TextUtils.isEmpty(mSa_float_num)) {
//                    Double wew = mark_price * integer;
                    Double wew = mark_price * integer * Double.valueOf(mContract_value);
                    DecimalFormat decFormat = new DecimalFormat("#,##0.0000");//格式化设置
                    String formt = decimalFormat.format(wew);

                    String trim = Tools.round(wew, Integer.valueOf(mSa_float_num)).toString().trim();
                    mTreatyPositionsTvPositionValue.setText(trim + "\t" + valuation);

                } else {

//                    Double wew = mark_price * integer;
                    Double wew = mark_price * integer * Double.valueOf(mContract_value);
                    DecimalFormat decFormat = new DecimalFormat("#,##0.0000");//格式化设置
                    String formt = decimalFormat.format(wew);
                    mTreatyPositionsTvPositionValue.setText(formt + "\t" + valuation);

                }


            } else {


//                Double wew = (1.0 / mark_price) * integer;
//                DecimalFormat decFormat = new DecimalFormat("#,##0.0000");//格式化设置
//                String formt = decimalFormat.format(wew);
//                mTreatyPositionsTvPositionValue.setText(formt + "\t" + valuation);

                if (!TextUtils.isEmpty(mSa_float_num)) {
                    Double wew = (1.0 / mark_price) * integer;
                    DecimalFormat decFormat = new DecimalFormat("#,##0.0000");//格式化设置
                    String formt = decimalFormat.format(wew);
                    String trim = Tools.round(wew, Integer.valueOf(mSa_float_num)).toString().trim();
                    mTreatyPositionsTvPositionValue.setText(trim + "\t" + valuation);

                } else {
                    Double wew = (1.0 / mark_price) * integer;
                    DecimalFormat decFormat = new DecimalFormat("#,##0.0000");//格式化设置
                    String formt = decimalFormat.format(wew);
                    mTreatyPositionsTvPositionValue.setText(formt + "\t" + valuation);
                }


            }
//
        }

    }

    private void getInfo() {
        isInfo = false;
        int num = (int) ((Math.random() * 9 + 1) * 100000);

        OkGo.<String>get(Config.MX_ACCOUNT + "?rnd=" + String.valueOf(num)).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body().toString();
                isInfo = true;
                Log.i("asxedfteffrr", result);

                try {
                    JSONObject jsonObj = new JSONObject(result);
                    if (jsonObj.getString("code").equals("1")) {
                        setMyFuturesInfo(result);

                    } else {

                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });


        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
        RequestParams params = new RequestParams();
        params.addHeader("app-version", Config.VERSION);
        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
        params.addHeader("my-client", "android");

        MyApplication.get().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.MX_ACCOUNT + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                isInfo = true;
                Log.i("asxedfteffrr", responseInfo.result);

                try {
                    JSONObject jsonObj = new JSONObject(responseInfo.result);
                    if (jsonObj.getString("code").equals("1")) {

                        setMyFuturesInfo(responseInfo.result);

                    } else {

                    }


                } catch (JSONException e) {
                    e.printStackTrace();

                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }

        });


    }

    private void setMyFuturesInfo(String result) {
        Gson gson = new Gson();
        MyFuturesInfo myFuturesInfo = gson.fromJson(result, MyFuturesInfo.class);
        List<MyFuturesInfo.DataBean.BalancesBean> balances = myFuturesInfo.getData().getBalances();


        for (int i = 0; i < balances.size(); i++) {
            String coin = balances.get(i).getCoin();
            if (valuation.equals(coin)) {
                mCang_yu_e = balances.get(i).getBalance();
                if (Double.valueOf(mCang_yu_e) == 0) {
                    mTreatyBehaviorTvRemainingBalance.setText("0.00" + "\t" + valuation);
                } else {
                    String trim = Tools.round(Double.valueOf(balances.get(i).getBalance()), Integer.valueOf(mSa_float_num)).toString().trim();
                    mTreatyBehaviorTvRemainingBalance.setText(trim + "\t" + valuation);
                }

            }
        }

    }

    private void getMyOrders(String Orders) {
        isOrders = false;
        int num = (int) ((Math.random() * 9 + 1) * 100000);


        OkGo.<String>get(Config.GET_MY_ORDERS + "?rnd=" + String.valueOf(num)).params("contract_id", Orders).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body().toString();
                isOrders = true;
                Log.i("bcnxbcnxbcxnbc", result);
                try {
                    JSONObject jsonObj = new JSONObject(result);
                    if (jsonObj.getString("code").equals("1")) {

                        setTreatyEntrusList(result);

                    } else {

                        if (mTreatyRecy != null && mEntrustListAdapter != null) {

                            mEntrustListAdapter.setEmptyView(R.layout.item_entrust_empty, mTreatyRecy);
                            mTreatyRecy.setAdapter(mEntrustListAdapter);
                        }

                        mTreatyBehaviorTvCurrentHistory.setText(getString(R.string.heyue_dangqian_wei_tuo) + "(0)");

                    }


                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });


//        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
//        String token = sharedPreferences.getString(Config.TOKEN, null);
//        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
//        RequestParams params = new RequestParams();
//        params.addHeader("app-version", Config.VERSION);
//        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
//        params.addHeader("my-client", "android");
//        params.addQueryStringParameter("contract_id", Orders);
//        MyApplication.get().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_MY_ORDERS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                isOrders = true;
//                Log.i("bcnxbcnxbcxnbc", responseInfo.result);
//                try {
//                    JSONObject jsonObj = new JSONObject(responseInfo.result);
//                    if (jsonObj.getString("code").equals("1")) {
//
//                        setTreatyEntrusList(responseInfo.result);
//
//                    } else {
//
//                        if (mTreatyRecy != null && mEntrustListAdapter != null) {
//
//                            mEntrustListAdapter.setEmptyView(R.layout.item_entrust_empty, mTreatyRecy);
//                            mTreatyRecy.setAdapter(mEntrustListAdapter);
//                        }
//
//                        mTreatyBehaviorTvCurrentHistory.setText(getString(R.string.heyue_dangqian_wei_tuo) + "(0)");
//
//                    }
//
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//            }
//
//        });
    }

    private void setTreatyEntrusList(String result) {

        Gson gson = new Gson();
        TreatyEntrustInfo treatyEntrustInfo = gson.fromJson(result, TreatyEntrustInfo.class);
        List<TreatyEntrustInfo.DataBean.OrderListsBean> order_lists = treatyEntrustInfo.getData().getOrder_lists();
//        mTreatyBehaviorTvCurrentHistory


        if (order_lists.size() == 0) {
            isShow = true;
            if (treaty_positions_tv_ganggan != null) {
                treaty_positions_tv_ganggan.setVisibility(View.VISIBLE);
            }

            mTreatyBehaviorTvCurrentHistory.setText(getString(R.string.heyue_dangqian_wei_tuo) + "(0)");
            order_lists.clear();
            if (mTreatyRecy != null && mEntrustListAdapter != null) {
                mEntrustListAdapter.setNewData(order_lists);
                mEntrustListAdapter.setEmptyView(R.layout.item_entrust_empty, mTreatyRecy);
                mTreatyRecy.setAdapter(mEntrustListAdapter);
            }


        } else {
            isShow = false;
            if (treaty_positions_tv_ganggan != null) {
                treaty_positions_tv_ganggan.setVisibility(View.INVISIBLE);
            }

            mTreatyBehaviorTvCurrentHistory.setText(getString(R.string.heyue_dangqian_wei_tuo) + "(" + String.valueOf(order_lists.size()) + ")");
            if (mTreatyRecy != null && mEntrustListAdapter != null) {
                if (!TextUtils.isEmpty(mIsreverse)) {
                    mEntrustListAdapter.SetIsZhen(mIsreverse);
                }

                if (!TextUtils.isEmpty(mSettle_anchor)) {
                    mEntrustListAdapter.setDanwei(mSettle_anchor);
                }

                if (!TextUtils.isEmpty(mSa_float_num)) {
                    mEntrustListAdapter.setNumber(mSa_float_num);
                }

                if (!TextUtils.isEmpty(mPrice_float_num)) {
                    mEntrustListAdapter.setPriceNumber(mPrice_float_num);
                }

                if (!TextUtils.isEmpty(mContract_value)) {
                    mEntrustListAdapter.setDanValue(mContract_value);
                }


                mEntrustListAdapter.setNewData(order_lists);
                mTreatyRecy.setAdapter(mEntrustListAdapter);
            }
        }

    }

    private void getListInfo(String orderbook) {

        isWeiTuo = false;
        int num = (int) ((Math.random() * 9 + 1) * 100000);

        OkGo.<String>get(Config.ORDERBOOK + "?rnd=" + String.valueOf(num)).params("contract_id", orderbook).params("depth", "5").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {

                String result = response.body().toString();
                isWeiTuo = true;
                Log.i("qwiuqiuwdsdbhuwey", result);
                try {
                    JSONObject jsonObj = new JSONObject(result);
                    if (jsonObj.getString("code").equals("1")) {
                        setDishList(result);
                    } else {

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });


//        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
//        String token = sharedPreferences.getString(Config.TOKEN, null);
//        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
//        RequestParams params = new RequestParams();
//        params.addHeader("app-version", Config.VERSION);
//        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
//        params.addHeader("my-client", "android");
//        params.addQueryStringParameter("contract_id", orderbook);
//        params.addQueryStringParameter("depth", "5");
//
//        MyApplication.get().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.ORDERBOOK + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                isWeiTuo = true;
//                Log.i("qwiuqiuwdsdbhuwey", responseInfo.result);
//
//                try {
//                    JSONObject jsonObj = new JSONObject(responseInfo.result);
//                    if (jsonObj.getString("code").equals("1")) {
//
//                        setDishList(responseInfo.result);
//
//                    } else {
//
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//            }
//
//        });

    }

    private void setDishList(String result) {

        Gson gson = new Gson();
        TreatyDishListInfo treatyDishListInfo = gson.fromJson(result, TreatyDishListInfo.class);
        List<TreatyDishListInfo.DataBean.LongBean> longX = treatyDishListInfo.getData().getLongX();
        List<TreatyDishListInfo.DataBean.ShortBean> shortX = treatyDishListInfo.getData().getShortX();
        Collections.sort(longX, new Comparator<TreatyDishListInfo.DataBean.LongBean>() {
            @Override
            public int compare(TreatyDishListInfo.DataBean.LongBean o1, TreatyDishListInfo.DataBean.LongBean o2) {

                String amount = o1.getAmount();
                String amount1 = o2.getAmount();
                Double one = Double.valueOf(amount);
                Double two = Double.valueOf(amount1);
                if (one > two) {
                    return -1;
                } else if (one < two) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });


        Collections.sort(shortX, new Comparator<TreatyDishListInfo.DataBean.ShortBean>() {
            @Override
            public int compare(TreatyDishListInfo.DataBean.ShortBean o1, TreatyDishListInfo.DataBean.ShortBean o2) {

                String amount = o1.getAmount();
                String amount1 = o2.getAmount();
                Double one = Double.valueOf(amount);
                Double two = Double.valueOf(amount1);
                if (one > two) {
                    return -1;
                } else if (one < two) {
                    return 1;
                } else {
                    return 0;
                }

            }
        });


        double one = 0;
        double two = 0;
        double max = 0;
        if (longX.size() > 0) {
            String amount = longX.get(0).getAmount();
            one = Double.valueOf(amount);
        }

        if (shortX.size() > 0) {
            String amount1 = shortX.get(0).getAmount();
            two = Double.valueOf(amount1);
        }

        if (one > two) {
            max = one;
        } else {
            max = two;
        }


        Collections.sort(longX, new Comparator<TreatyDishListInfo.DataBean.LongBean>() {
            @Override
            public int compare(TreatyDishListInfo.DataBean.LongBean o1, TreatyDishListInfo.DataBean.LongBean o2) {

                String amount = o1.getPrice();
                String amount1 = o2.getPrice();
                Double one = Double.valueOf(amount);
                Double two = Double.valueOf(amount1);
                if (one > two) {
                    return -1;
                } else if (one < two) {
                    return 1;
                } else {
                    return 0;
                }


            }
        });


        Collections.sort(shortX, new Comparator<TreatyDishListInfo.DataBean.ShortBean>() {
            @Override
            public int compare(TreatyDishListInfo.DataBean.ShortBean o1, TreatyDishListInfo.DataBean.ShortBean o2) {

                String amount = o1.getPrice();
                String amount1 = o2.getPrice();
                Double one = Double.valueOf(amount);
                Double two = Double.valueOf(amount1);


                if (one > two) {
                    return -1;
                } else if (one < two) {
                    return 1;
                } else {
                    return 0;
                }

            }
        });


        ArrayList<TreatyDishListInfo.DataBean.ShortBean> shortBeen = new ArrayList<>();

        for (int i = 0; i < shortX.size(); i++) {
            TreatyDishListInfo.DataBean.ShortBean shortBean = new TreatyDishListInfo.DataBean.ShortBean();
            String amount = shortX.get(i).getAmount();
            Double aDouble = Double.valueOf(amount);
            if (aDouble != 0) {
                shortBean.setAmount(shortX.get(i).getAmount());
                shortBean.setSum_amount(shortX.get(i).getSum_amount());
                shortBean.setPrice(shortX.get(i).getPrice());
                shortBeen.add(shortBean);
            }

        }


        ArrayList<TreatyDishListInfo.DataBean.LongBean> longBeens = new ArrayList<>();
        for (int i = 0; i < longX.size(); i++) {

            TreatyDishListInfo.DataBean.LongBean longBean = new TreatyDishListInfo.DataBean.LongBean();
            if (Double.valueOf(longX.get(i).getAmount()) != 0) {
                longBean.setPrice(longX.get(i).getPrice());
                longBean.setAmount(longX.get(i).getAmount());
                longBean.setSum_amount(longX.get(i).getSum_amount());

                longBeens.add(longBean);
            }


        }

        if (shortBeen.size() > 0 && longBeens.size() > 0) {

            Log.i("wuehfiwuheifwe", shortBeen.get(shortBeen.size() - 1).getPrice());
            Log.i("jhfjshdshdsdsd", longBeens.get(0).getPrice());
            Config.SELL_YI = shortBeen.get(shortBeen.size() - 1).getPrice();
            Config.BUY_YI = longBeens.get(0).getPrice();
        }


        if (mTreatyRecySell != null && mEntrustListsellAdapter != null) {

            if (!TextUtils.isEmpty(mPrice_float_num)) {
                mEntrustListsellAdapter.setNumber(mPrice_float_num);
            }
            mEntrustListsellAdapter.setValue(max);
            if (!TextUtils.isEmpty(mIsreverse)) {
                mEntrustListsellAdapter.setIsreverse(mIsreverse);
            }

            if (!TextUtils.isEmpty(mSa_float_num)) {
                mEntrustListsellAdapter.setIsreverseNumber(mSa_float_num);
            }
            if (!TextUtils.isEmpty(mContract_value)) {
                mEntrustListsellAdapter.setContractValue(mContract_value);
            }

            mEntrustListsellAdapter.settype(changeType);
            mEntrustListsellAdapter.setNewData(shortBeen);
            mTreatyRecySell.setAdapter(mEntrustListsellAdapter);

        }


        if (mTreatyRecyBuy != null && mEntrustListbuyAdapter != null) {
            if (!TextUtils.isEmpty(mPrice_float_num)) {
                mEntrustListbuyAdapter.setNumber(mPrice_float_num);
            }
            if (!TextUtils.isEmpty(mIsreverse)) {
                mEntrustListbuyAdapter.setIsreverse(mIsreverse);
            }

            if (!TextUtils.isEmpty(mSa_float_num)) {
                mEntrustListbuyAdapter.setIsreverseNumber(mSa_float_num);
            }

            if (!TextUtils.isEmpty(mContract_value)) {
                mEntrustListbuyAdapter.setContractValue(mContract_value);
            }

            mEntrustListbuyAdapter.SetValue(max);
            mEntrustListbuyAdapter.settype(changeType);
            mEntrustListbuyAdapter.setNewData(longBeens);
            mTreatyRecyBuy.setAdapter(mEntrustListbuyAdapter);
        }


    }

    private void initRecy() {

        ArrayList<String> strings = new ArrayList<>();

        for (int i = 0; i < 20; i++) {
            strings.add("");
        }

        mEntrustListAdapter = new EntrustListAdapter(null);
        mEntrustListsellAdapter = new EntrustListsellAdapter(null);
        mEntrustListbuyAdapter = new EntrustListbuyAdapter(null);

//        当前委托
        if (mTreatyRecy != null) {
            mTreatyRecy.setLayoutManager(new LinearLayoutManager(getActivity()));
            mTreatyRecy.setAdapter(mEntrustListAdapter);
        }

//        看空
        if (mTreatyRecySell != null) {
            mTreatyRecySell.setLayoutManager(new LinearLayoutManager(getActivity()));
            mTreatyRecySell.setAdapter(mEntrustListsellAdapter);
        }

//        看多
        if (mTreatyRecyBuy != null) {
            mTreatyRecyBuy.setLayoutManager(new LinearLayoutManager(getActivity()));
            mTreatyRecyBuy.setAdapter(mEntrustListbuyAdapter);
        }

    }

    private void initStatPositions() {

        mTreatyBehaviorTvHistory.setSelected(false);
        mTreatyTvHistory.setSelected(false);
        mTreatyBehaviorTvCurrentHistory.setSelected(false);
    }


    private void initOnclikListener() {


        mTreatyTvIndexPrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String trim = mTreatyTvIndexPrice.getText().toString().trim();
                mTreatyBehaviorEdPrice.setText(trim);
            }
        });

        mTrearyButZhang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTreatyBehaviorEdPrice.setText("");
                mTreatyBehaviorEdNumber.setText("");
                changeType = "1";
                isZhang = "1";
                setBotton();
                mTrearyButZhang.setSelected(true);
//                mTrearyLeverShuliangType.setText("数量(张)");
                mTrearyLeverShuliangType.setText(getString(num) + "(" + getString(R.string.zhang) + ")");
                mTreatyBehaviorEdNumber.setHint(getString(num));
                mTreatyBehaviorTvNumber.setText(getString(R.string.zhang));
                mTreatyBehaviorEdNumber.setInputType(TYPE_CLASS_NUMBER | TYPE_NUMBER_VARIATION_NORMAL);
                if (mTreatyRecyBuy != null && mEntrustListbuyAdapter != null) {
                    mEntrustListbuyAdapter.settype("1");
                    mEntrustListbuyAdapter.notifyDataSetChanged();
                }


                if (mTreatyRecySell != null && mEntrustListsellAdapter != null) {

                    mEntrustListsellAdapter.settype("1");
                    mEntrustListsellAdapter.setIsreverse(mIsreverse);
                    mEntrustListsellAdapter.notifyDataSetChanged();

                }

            }
        });

        mTrearyButBtc.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mTreatyBehaviorEdPrice.setText("");
                mTreatyBehaviorEdNumber.setText("");
                changeType = "2";
                isZhang = "2";
                setBotton();
                mTrearyButBtc.setSelected(true);
                mTreatyBehaviorEdNumber.setHint(R.string.heyue_jiazhi);
                mTreatyBehaviorEdNumber.setInputType(TYPE_CLASS_NUMBER | TYPE_NUMBER_FLAG_DECIMAL);
                mTreatyBehaviorTvNumber.setText(valuation);
                mTrearyLeverShuliangType.setText(getString(num) + "(" + valuation + ")");
                if (mTreatyRecyBuy != null && mEntrustListbuyAdapter != null) {
                    mEntrustListbuyAdapter.settype("2");
                    mEntrustListbuyAdapter.notifyDataSetChanged();
                }


                if (mTreatyRecySell != null && mEntrustListsellAdapter != null) {

                    mEntrustListsellAdapter.settype("2");
                    mEntrustListsellAdapter.setIsreverse(mIsreverse);
                    mEntrustListsellAdapter.notifyDataSetChanged();

                }

            }
        });


        mTreatyTvNewIndex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), WebActivity.class).putExtra("web_url", Config.URL + "mx/tradeGuide/indexPrice"));

            }
        });

        mTreatyTvHeliPrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), WebActivity.class).putExtra("web_url", Config.URL + "mx/tradeGuide/fairPriceMarking"));

            }
        });


//        历史扩大
        mTreatyBehaviorTvHistoryLin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), HistoryActivity.class).putExtra("type", refreshType));
            }
        });

//        当前委托

        mTreatyBehaviorTvCurrentHistoryLin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SetStat();
                mTreatyRecy.setVisibility(View.VISIBLE);

                initStatPositions();
                mTreatyBehaviorTvCurrentHistory.setSelected(true);

            }
        });

//        仓位扩大
        mTreatyTvHistoryLin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initStatPositions();
                mTreatyTvHistory.setSelected(true);

                if (mPosition_lists != null) {

                    if (mPosition_lists.size() > 0) {

                        if (mPosition_lists.get(0).getAmount().equals("0")) {
                            SetStat();
                            mIncludeEmptyPositions.setVisibility(View.VISIBLE);
                        } else {
                            SetStat();
                            mIncludePositions.setVisibility(View.VISIBLE);
                        }


                    } else {

                        SetStat();
                        mIncludeEmptyPositions.setVisibility(View.VISIBLE);
                    }

                } else {
                    SetStat();
                    mIncludeEmptyPositions.setVisibility(View.VISIBLE);
                }

            }
        });


//        看多列表
        mEntrustListbuyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TreatyDishListInfo.DataBean.LongBean longBean = (TreatyDishListInfo.DataBean.LongBean) adapter.getData().get(position);
                String amount = longBean.getAmount();
                String price = longBean.getPrice();
                if (!TextUtils.isEmpty(mPrice_float_num)) {

                    String trim = Tools.round(Double.valueOf(price), Integer.valueOf(mPrice_float_num)).toString().trim();
                    mTreatyBehaviorEdPrice.setText(trim);
                } else {
                    mTreatyBehaviorEdPrice.setText(price);
                }
            }
        });

//    看空列表
        mEntrustListsellAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TreatyDishListInfo.DataBean.ShortBean shortBean = (TreatyDishListInfo.DataBean.ShortBean) adapter.getData().get(position);
                String amount = shortBean.getAmount();
                String price = shortBean.getPrice();
                if (!TextUtils.isEmpty(mPrice_float_num)) {
                    String trim = Tools.round(Double.valueOf(price), Integer.valueOf(mPrice_float_num)).toString().trim();
                    mTreatyBehaviorEdPrice.setText(trim);
                } else {
                    mTreatyBehaviorEdPrice.setText(price);
                }
            }
        });


//        调整杠杆
        treaty_positions_tv_ganggan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mStrings != null) {
                    if (mContract_id != null) {
//                        if ("1".equals(mAllow_cross)) {
//
//                            new LeverDialog(getActivity(), mStrings, mContract_id, mLeverage, mIs_cross, mAllow_cross, mSa_float_num).show();
//                        } else {
//
//                            new NoLeverDialog(getActivity(), mStrings, mContract_id, mLeverage, mIs_cross, mAllow_cross, mSa_float_num).show();
//                        }

//                        new CangweiMoshiDialog(getActivity(), mStrings, mContract_id, mLeverage, mIs_cross, mAllow_cross, mSa_float_num).show();
                        new MoShiDialog(getActivity(), mStrings, mContract_id, mLeverage, mIs_cross, mAllow_cross, mSa_float_num, mPrice_float_num).show();

                    }

                }


            }
        });


//        市场切换
        treary_name_type_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                setPop();

            }
        });

//        资金转换
        mTreatyBehaviorTvChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
                boolean aBoolean = sharedPreferences.getBoolean(Config.KEY_IS_LOGIN, false);

                if (aBoolean) {
                    startActivity(new Intent(getActivity(), MoneyTransfersActivity.class).putExtra("mSettle_anchor", mSettle_anchor));
                } else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
//                    distinct
                }

            }
        });
//        增加保证金
        mTreatyPositionsLinTiaozheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!TextUtils.isEmpty(mIs_cross)) {
                    if (mIs_cross.equals("1")) {
                        Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), "全仓不可调整");
                    } else {
                        if (mPosition_lists != null) {
                            String position_id = mPosition_lists.get(0).getPosition_id();
                            new EarnestDialog(getActivity(), position_id, valuation, mSa_float_num).show();
                        }
                    }
                }

//                if (mPosition_lists != null) {
//                    String position_id = mPosition_lists.get(0).getPosition_id();
//                    new EarnestDialog(getActivity(), position_id, valuation, mSa_float_num).show();
//                }


            }
        });

//        平仓
        mTreatyPositionsLinPing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mUnwindInfo != null) {

                    String direction = mUnwindInfo.getData().getPosition_lists().get(0).getDirection();
                    String amount = mUnwindInfo.getData().getPosition_lists().get(0).getAmount();
                    String leverage = mUnwindInfo.getData().getPosition_lists().get(0).getLeverage();
                    String price = mUnwindInfo.getData().getPosition_lists().get(0).getPrice();
                    String symbol = mUnwindInfo.getData().getPosition_lists().get(0).getContract_symbol();
                    String contract_id = mUnwindInfo.getData().getPosition_lists().get(0).getContract_id();
                    String is_cross = mUnwindInfo.getData().getPosition_lists().get(0).getIs_cross();
//                    new UnwindDialog(getActivity(), direction, amount, leverage, price, valuation, symbol, contract_id, is_cross, mContract_anchor).show();
                    new UnwindDialog(getActivity(), direction, amount, leverage, price, valuation, mQuote_anchor, contract_id, is_cross, mContract_anchor, mPrice_float_num).show();
                }

            }
        });

//        K线
        mTrearyCheckTvKine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                handler.removeCallbacksAndMessages(null);
                Intent intent = new Intent(getActivity(), FuturesKLineActivity.class);
                intent.putExtra("pair", mPair);
                intent.putExtra("contract_id", refreshType);
                startActivity(intent);
            }
        });

//     张数类型切换
        mTrearyCheckDanweiLin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (!TextUtils.isEmpty(mAllow_cross)) {

                    if (mAllow_cross.equals("1")) {

                        if (isOncilk || !isShow) {

                            Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), "有仓位和委托不可调整");

                        } else {

                            UnitsDialog unitsDialog = new UnitsDialog(getActivity(), valuation);
                            unitsDialog.setListener(new UnitsDialog.getLIstener() {
                                @Override
                                public void get(String data, String type) {
                                    treary_check_danwei_tv.setText(data);
                                }
                            });
                            unitsDialog.show();
                        }

                    } else {

                        Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), "该合约只支持逐仓");
                    }

                }


            }
        });

//        计算器
        mTreatyJisuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                Util.showSnachBar(getActivity(), getResources().getColor(R.color.green), "操作成功");

                startActivity(new Intent(getActivity(), CounterCorrectActivity.class));
            }
        });

//        更多设置
        mTreatyMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TreatySetDialog(getActivity()).show();
            }
        });

//        历史委托
        mTreatyBehaviorTvHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(getActivity(), HistoryActivity.class).putExtra("type", refreshType));

            }
        });

//        仓位
        mTreatyTvHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                initStatPositions();
                mTreatyTvHistory.setSelected(true);

                if (mPosition_lists != null) {

                    if (mPosition_lists.size() > 0) {

                        if (mPosition_lists.get(0).getAmount().equals("0")) {
                            SetStat();
                            mIncludeEmptyPositions.setVisibility(View.VISIBLE);
                        } else {
                            SetStat();
                            mIncludePositions.setVisibility(View.VISIBLE);
                        }


                    } else {

                        SetStat();
                        mIncludeEmptyPositions.setVisibility(View.VISIBLE);
                    }

                } else {
                    SetStat();
                    mIncludeEmptyPositions.setVisibility(View.VISIBLE);
                }


            }
        });


//        当前委托
        mTreatyBehaviorTvCurrentHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SetStat();
                mTreatyRecy.setVisibility(View.VISIBLE);

                initStatPositions();
                mTreatyBehaviorTvCurrentHistory.setSelected(true);
            }
        });


//        市价 限价 单切换
        mTrearyCheckPriceLin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new CheckPriceDialog(getActivity()).show();
            }
        });

//        杠杆切换
        mTrearyLeverLin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isOncilk || !isShow) {
                    Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), "有仓位和委托不可调整");
                } else {
                    if (mStrings != null) {

                        LeverSetDialog leverSetDialog = new LeverSetDialog(getActivity(), mStrings, mAllow_cross);
                        leverSetDialog.getValue(new LeverSetDialog.getValueLIstener() {
                            @Override
                            public void get(String data) {
                                mLeverage = data;
                                String price = mTreatyBehaviorEdPrice.getText().toString().trim();
                                String number = mTreatyBehaviorEdNumber.getText().toString().trim();
                                if (!TextUtils.isEmpty(price) && !TextUtils.isEmpty(number)) {
                                    getCost(price, number);
                                }
                                if (data.equals(getString(R.string.heyue_quancang))) {
                                    mTrearyLeverTv.setText(data);
                                } else {
                                    mTrearyLeverTv.setText(data + "X");
                                }
                            }
                        });

                        leverSetDialog.show();
                    }
                }


            }
        });

//        监听mTreatyBehaviorEdNumber焦点
        mTreatyBehaviorEdNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    treaty_behavior_lin_number.setBackground(getResources().getDrawable(R.drawable.shape_otc_rd_selec_doub));
                } else {
                    treaty_behavior_lin_number.setBackground(getResources().getDrawable(R.drawable.shape_otc_ed));
                }
            }
        });

//        数量
        mTreatyBehaviorEdNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {


            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                judge(s);

                try {

                    double entrustValue = getEntrustValue();

                    if (entrustValue != 0) {
                        try {
                            String trim = Tools.round(entrustValue, Integer.valueOf(mSa_float_num)).toString().trim();
                            mTreatyBehaviorTvEntrustValue.setText(trim + "\t" + valuation);

                        } catch (NumberFormatException e) {

                        }
                    }
                    mNumber = s.toString();

                    if (!TextUtils.isEmpty(s)) {
                        mTreatyNumber = Double.valueOf(mNumber);
                        if (mTreatyPrice > 0) {

                            new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    //耗时操作
                                    Message message = new Message();
                                    message.what = 3;
                                    handlers.sendMessage(message);
                                }
                            }).start();


//                            getCost(String.valueOf(mTreatyPrice), String.valueOf(mTreatyNumber));
                        }

                    } else {
                        mTreatyNumber = 0;
                        mTreatyBehaviorTvLongPrice.setText(getString(R.string.heyue_chengben) + "0.00" + "\t" + valuation);
                        mTreatyBehaviorButShortPrice.setText(getString(R.string.heyue_chengben) + "0.00" + "\t" + valuation);
                        mTreatyBehaviorTvEntrustValue.setText("0.00" + "\t" + valuation);
                    }


                } catch (Exception e) {

                }


            }


        });

//        监听mTreatyBehaviorEdPrice焦点变化
        mTreatyBehaviorEdPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    treaty_behavior_ed_lin_price.setBackground(getResources().getDrawable(R.drawable.shape_otc_rd_selec_doub));
                } else {
                    treaty_behavior_ed_lin_price.setBackground(getResources().getDrawable(R.drawable.shape_otc_ed));
                }
            }
        });

//        价格

        mTreatyBehaviorEdPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                judge(s);

                try {


                    if (!TextUtils.isEmpty(s)) {
                        mPrice = s.toString();
                        mTreatyPrice = Double.valueOf(mPrice);
                        if (mTreatyNumber > 0) {
//                        getCost(mTreatyPrice, mTreatyNumber);


                            new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    //                耗时操作
                                    Message message = new Message();
                                    message.what = 3;
                                    handlers.sendMessage(message);
                                }
                            }).start();

//                            getCost(String.valueOf(mTreatyPrice), String.valueOf(mTreatyNumber));
                        }
                    } else {
                        mTreatyPrice = 0;
                        mTreatyBehaviorTvLongPrice.setText(getString(R.string.heyue_chengben) + "0.00" + "\t" + valuation);
                        mTreatyBehaviorButShortPrice.setText(getString(R.string.heyue_chengben) + "0.00" + "\t" + valuation);
                        mTreatyBehaviorTvEntrustValue.setText("0.00" + "\t" + valuation);
                    }


                } catch (Exception e) {

                }


                double entrustValue = getEntrustValue();
                if (entrustValue != 0) {

//                    DecimalFormat decimalFormat = new DecimalFormat("#,##0.0000");//格式化设置
//                    String format = decimalFormat.format(entrustValue);
                    try {

                        String trim = Tools.round(entrustValue, Integer.valueOf(mSa_float_num)).toString().trim();
                        mTreatyBehaviorTvEntrustValue.setText(trim + "\t" + valuation);

                    } catch (NumberFormatException e) {

                    }


                }


            }
        });


//        做空
        mTreatyBehaviorButShort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
                boolean aBoolean = sharedPreferences.getBoolean(Config.KEY_IS_LOGIN, false);

                if (aBoolean) {


                    if (isLimit.equals(getString(R.string.heyue_xianjia_shijia)) || isLimit.equals("")) {

                        if (mTreatyPrice != 0 && mTreatyNumber != 0) {

                            new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    //                耗时操作
                                    Message message = new Message();
                                    message.what = 1;
                                    handlers.sendMessage(message);
                                }
                            }).start();

//                            setContractorders(mTreatyPrice, mTreatyNumber, "-1");

                        } else {
//                            Snackbar snackbar = Util.ShortSnackbar(mTreatyTvHistory, "价格或数量不能为空", Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//                            snackbar.show();
                            Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), "价格或数量不能为空");

                        }
                    } else {

                        if (mTreatyNumber != 0) {
                            new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    //耗时操作
                                    Message message = new Message();
                                    message.what = 1;
                                    handlers.sendMessage(message);
                                }
                            }).start();

//                            setContractorders(mTreatyPrice, mTreatyNumber, "-1");

                        } else {
//                            Snackbar snackbar = Util.ShortSnackbar(mTreatyTvHistory, "数量不能为空", Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//                            snackbar.show();
                            Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), "价格或数量不能为空");
                        }
                    }


                } else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
            }


        });


//        做多
        mTreatyBehaviorButLong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
                boolean aBoolean = sharedPreferences.getBoolean(Config.KEY_IS_LOGIN, false);

                if (aBoolean) {

                    Log.i("wlkfiwjofjw", isLimit);

                    if (isLimit.equals(getString(R.string.heyue_xianjia_shijia)) || isLimit.equals("")) {

                        if (mTreatyPrice != 0 && mTreatyNumber != 0) {


                            new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    //                耗时操作
                                    Message message = new Message();
                                    message.what = 2;
                                    handlers.sendMessage(message);
                                }
                            }).start();

//                            setContractorders(mTreatyPrice, mTreatyNumber, "1");

                        } else {
//                            Snackbar snackbar = Util.ShortSnackbar(mTreatyTvHistory, "价格或数量不能为空", Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//                            snackbar.show();
                            Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), "价格或数量不能为空");
                        }
                    } else {

                        if (mTreatyNumber != 0) {

                            new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    //                耗时操作
                                    Message message = new Message();
                                    message.what = 2;
                                    handlers.sendMessage(message);
                                }
                            }).start();

//                            setContractorders(mTreatyPrice, mTreatyNumber, "1");

                        } else {
//                            Snackbar snackbar = Util.ShortSnackbar(mTreatyTvHistory, "数量不能为空", Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//                            snackbar.show();
                            Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), "价格或数量不能为空");
                        }
                    }

                } else {

                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }

            }
        });


        if (mEntrustListAdapter != null) {

        }


//        取消委托
        mEntrustListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                TreatyEntrustInfo.DataBean.OrderListsBean orderListsBean = (TreatyEntrustInfo.DataBean.OrderListsBean) adapter.getData().get(position);
                setDissEntrust(orderListsBean.getOrder_id());
            }
        });

    }

    private void getCost(String treatyPrice, String treatyNumber) {


        if (mIsreverse.equals("1")) {
//            反向
            if (!isZhang.equals("1")) {

                double v = Double.valueOf(treatyNumber) * (Double.valueOf(treatyPrice) / Double.valueOf(mContract_value));
                String trim = Tools.round(v, 6).toString().trim();
                treatyNumber = trim;
//                double v = Double.valueOf(treatyNumber) * Double.valueOf(treatyPrice) / Double.valueOf(mContract_value);
//                String trim = Tools.round(v, 6).toString().trim();
            }

        } else {

            if (!isZhang.equals("1")) {

                double value = Double.valueOf(treatyNumber) / (Double.valueOf(treatyPrice) * Double.valueOf(mContract_value));
                String trim = Tools.round(value, 6).toString().trim();
                treatyNumber = trim;
            }


        }


//        if (!isZhang.equals("1")) {
//
//            Log.i("wkehfhweifuhw", "1");
//
//            double v = Double.valueOf(treatyNumber) * Double.valueOf(treatyPrice) / Double.valueOf(mContract_value);
//            String trim = Tools.round(v, 6).toString().trim();
//            treatyNumber = trim;
//        }


        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("contract_id", refreshType);
        params.addQueryStringParameter("price", treatyPrice);
        params.addQueryStringParameter("num", treatyNumber);
//        params.addQueryStringParameter("direction", "1");
        params.addQueryStringParameter("leverage", mLeverage);


        int num = (int) ((Math.random() * 9 + 1) * 100000);
        MyApplication.get().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.CAL_ORDER_MARGIN + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.i("xnbdsjdsdhu", responseInfo.result);

                try {
                    JSONObject jsonObject = new JSONObject(responseInfo.result);

                    if (jsonObject.getString("code").equals("1")) {

                        setCostInfo(responseInfo.result);

                    }

                } catch (JSONException e) {


                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }

        });
    }

    private void setCostInfo(String result) {

        Gson gson = new Gson();
        CostInfo costInfo = gson.fromJson(result, CostInfo.class);


        if (Double.valueOf(costInfo.getData().getLong_im()) == 0) {
            mTreatyBehaviorTvLongPrice.setText(getString(R.string.heyue_chengben) + "0.00" + "\t" + valuation);
        } else {
            String tvlongprice = Tools.round(Double.valueOf(costInfo.getData().getLong_im()), Integer.valueOf(mSa_float_num)).toString().trim();
            mTreatyBehaviorTvLongPrice.setText(getString(R.string.heyue_chengben) + tvlongprice + "\t" + valuation);
        }

//        if (costInfo.getData().getLong_im().equals("0")) {
//            mTreatyBehaviorTvLongPrice.setText(getString(R.string.heyue_chengben) + "0.00" + "\t" + valuation);
//        } else {
//            String tvlongprice = Tools.round(Double.valueOf(costInfo.getData().getLong_im()), Integer.valueOf(mSa_float_num)).toString().trim();
//            mTreatyBehaviorTvLongPrice.setText(getString(R.string.heyue_chengben) + tvlongprice + "\t" + valuation);
//        }


        if (Double.valueOf(costInfo.getData().getShort_im()) == 0) {
            mTreatyBehaviorButShortPrice.setText(getString(R.string.heyue_chengben) + "0.00" + "\t" + valuation);
        } else {
            String shortprice = Tools.round(Double.valueOf(costInfo.getData().getShort_im()), Integer.valueOf(mSa_float_num)).toString().trim();
            mTreatyBehaviorButShortPrice.setText(getString(R.string.heyue_chengben) + shortprice + "\t" + valuation);
        }

//
//        if (costInfo.getData().getShort_im().equals("0")) {
//            mTreatyBehaviorButShortPrice.setText(getString(R.string.heyue_chengben) + "0.00" + "\t" + valuation);
//        } else {
//            String shortprice = Tools.round(Double.valueOf(costInfo.getData().getShort_im()), Integer.valueOf(mSa_float_num)).toString().trim();
//            mTreatyBehaviorButShortPrice.setText(getString(R.string.heyue_chengben) + shortprice + "\t" + valuation);
//        }

//        mTreatyBehaviorTvLongPrice.setText(getString(R.string.heyue_chengben) + costInfo.getData().getLong_im() + "\t" + valuation);
//        mTreatyBehaviorButShortPrice.setText(getString(R.string.heyue_chengben) + costInfo.getData().getShort_im() + "\t" + valuation);


    }

    private void setDissEntrust(String order_id) {


        final MicroAVLIDialog microAVLIDialog = new MicroAVLIDialog(getActivity());
        microAVLIDialog.show();


        OkGo.<String>post(Config.CANCEL_ORDER).params("order_id", order_id).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body().toString();

                if (microAVLIDialog != null) {
                    microAVLIDialog.dismiss();
                }

                Log.i("hsajhsajhsjahsjahs", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);

                    if (jsonObject.getString("code").equals("1")) {
                        getListInfo(refreshType);
                        getMyOrders(refreshType);


                        Util.showSnachBar(getActivity(), getResources().getColor(R.color.bg_green), "取消成功");
                        if (handler != null) {
                            handler.postDelayed(runnable, 0);
                        }

                    } else {

                        Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), jsonObject.getString("info"));
                    }
                } catch (JSONException e) {


                }

            }
        });

//        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
//        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
//        RequestParams params = new RequestParams();
//        params.addHeader("app-version", Config.VERSION);
//        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
//        params.addHeader("my-client", "android");
//        params.addBodyParameter("order_id", order_id);
//
//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.CANCEL_ORDER, params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//                microAVLIDialog.dismiss();
//
//                Log.i("hsajhsajhsjahsjahs", responseInfo.result);
//                try {
//                    JSONObject jsonObject = new JSONObject(responseInfo.result);
//
//                    if (jsonObject.getString("code").equals("1")) {
//                        getListInfo(refreshType);
//                        getMyOrders(refreshType);
//
//                        Util.showSnachBar(getActivity(), getResources().getColor(R.color.bg_green), "取消成功");
//                    } else {
//
//                        Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), jsonObject.getString("info"));
//                    }
//                } catch (JSONException e) {
//
//
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//            }
//
//        });
    }

    private void setContractorders(double treatyPrice, double treatyNumber, String type) {
//        handler.removeCallbacksAndMessages(null);
//        handlers.removeCallbacksAndMessages(null);

        final MicroAVLIDialog microAVLIDialog = new MicroAVLIDialog(getActivity());
        microAVLIDialog.show();

//        mIsreverse 是否正反向
        String name = treary_check_danwei_tv.getText().toString().trim();

        if (mIsreverse.equals("1")) {
//            反向
            if (!isZhang.equals("1")) {
                double v = Double.valueOf(mTreatyBehaviorEdNumber.getText().toString().trim()) * Double.valueOf(mPrice) / Double.valueOf(mContract_value);
                String trim = Tools.round(v, 6).toString().trim();
                mNumber = trim;
            }
        } else {
//            正向
            if (!isZhang.equals("1")) {
                double v = Double.valueOf(mTreatyBehaviorEdNumber.getText().toString().trim()) / Double.valueOf(mPrice) / Double.valueOf(mContract_value);
                String trim = Tools.round(v, 6).toString().trim();
                mNumber = trim;
            }
        }

        String is_cross;
        String limitType;
//        treary_check_danwei_tv
        String trim = treary_check_danwei_tv.getText().toString().trim();

        if (getString(R.string.heyue_quancang).equals(trim)) {

            is_cross = "1";
        } else {

            is_cross = "-1";

        }
//        限价市价
        if (isLimit.equals(getString(R.string.heyue_xianjia_shijia)) || isLimit.equals("")) {
            limitType = "limit";
        } else {
            limitType = "market";
        }


        OkGo.<String>post(Config.PLACE_ORDER).params("contract_id", refreshType).params("price", mPrice).params("amount", mNumber).params("leverage", mLeverage).params("direction", type).params("type", limitType).params("is_cross", is_cross).params("source", "android").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body().toString();
                if (microAVLIDialog != null) {
                    microAVLIDialog.dismiss();

                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.getString("code").equals("1")) {

                            mTreatyBehaviorEdPrice.setText("");
                            mTreatyBehaviorEdNumber.setText("");

                            Util.showSnachBar(getActivity(), getResources().getColor(R.color.bg_green), "下单成功");
                            if (handler != null) {
                                handler.postDelayed(runnable, 0);
                            }

                            getMyPositions(refreshType);
                            getMyOrders(refreshType);
                        } else {
                            Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), jsonObject.getString("info"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

//        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
//        String token = sharedPreferences.getString(Config.TOKEN, null);
//        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
//        RequestParams params = new RequestParams();
//        params.addHeader("app-version", Config.VERSION);
//        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
//        params.addHeader("my-client", "android");
//        params.addHeader("source", "android");
//        params.addBodyParameter("contract_id", refreshType);
//        params.addBodyParameter("price", mPrice);
//        params.addBodyParameter("amount", mNumber);
//        params.addBodyParameter("leverage", mLeverage);
//        params.addBodyParameter("direction", type);
//        params.addBodyParameter("type", limitType);
//        params.addBodyParameter("lang", "zh_cn");
//        params.addBodyParameter("is_cross", is_cross);
//        params.addBodyParameter("source", "android");
//
//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.PLACE_ORDER, params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//                handler.postDelayed(runnable, 0);
//
//                Log.i("kajaqiwdhqiwdqoiud", responseInfo.result);
//
//                microAVLIDialog.dismiss();
//
//                try {
//                    JSONObject jsonObject = new JSONObject(responseInfo.result);
//                    if (jsonObject.getString("code").equals("1")) {
//
//                        mTreatyBehaviorEdPrice.setText("");
//                        mTreatyBehaviorEdNumber.setText("");
//
//                        Util.showSnachBar(getActivity(), getResources().getColor(R.color.bg_green), "下单成功");
//                        getMyPositions(refreshType);
//                        getMyOrders(refreshType);
//                    } else {
//                        Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), jsonObject.getString("info"));
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//                handler.postDelayed(runnable, 0);
//
//            }
//
//        });


    }


    //    获取所有期货信息
    public void getFuturesInfo() {

        isFuturesInfo = false;
        int num = (int) ((Math.random() * 9 + 1) * 100000);


        OkGo.<String>get(Config.GET_MX_CONTRACTS + "?rnd=" + String.valueOf(num)).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body().toString();
                isFuturesInfo = true;
                Log.i("wuyeuwyeuwyeuwye", result);

                try {

                    JSONObject jsonObj = new JSONObject(result);
                    if (jsonObj.getString("code").equals("1")) {
                        Gson gson = new Gson();
                        mFuturesListInfo = gson.fromJson(result, FuturesListInfo.class);
                    } else {

                    }

                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });


//        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
//        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
//        RequestParams params = new RequestParams();
//        MyApplication.get().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_MX_CONTRACTS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                isFuturesInfo = true;
//                Log.i("wuyeuwyeuwyeuwye", responseInfo.result);
//
//                try {
//
//                    JSONObject jsonObj = new JSONObject(responseInfo.result);
//                    if (jsonObj.getString("code").equals("1")) {
//
//                        Gson gson = new Gson();
//                        mFuturesListInfo = gson.fromJson(responseInfo.result, FuturesListInfo.class);
//
//                    } else {
//
//                    }
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//
//            }
//
//        });


    }


    public void SetStat() {

        if (mIncludePositions != null) {
            mIncludePositions.setVisibility(View.GONE);
        }

        if (mIncludeEmptyPositions != null) {
            mIncludeEmptyPositions.setVisibility(View.GONE);
        }

        if (mTreatyRecy != null) {
            mTreatyRecy.setVisibility(View.GONE);
        }


    }

    @Override
    public void setData() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        OkGo.getInstance().cancelTag(this);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mIsVisibleToUser = true;
        handler.postDelayed(runnable, 0);

    }


    @Override
    public void onPause() {
        super.onPause();
        mIsVisibleToUser = false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        mIsVisibleToUser = isVisibleToUser;
        if (mIsVisibleToUser) {
            handler.postDelayed(runnable, 0);
        }
    }


    private Handler handler = new Handler() {

    };
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {


            Log.i("weuhfiwuhefiwhef", "12121");

            if (mIsVisibleToUser) {
                if (isInfo) {
                    getInfo();
                } else {
                    Log.i("uwyeuywewuyeu", "getInfo");
                }

//                if (isWeiTuo) {
//                    getListInfo(refreshType);
//                } else {
//                    Log.i("uwyeuywewuyeu", "getListInfo");
//                }

                if (isPositions) {
                    getMyPositions(refreshType);
                } else {
                    Log.i("uwyeuywewuyeu", "getMyPositions");
                }

                if (isOrders) {
                    getMyOrders(refreshType);
                } else {
                    Log.i("uwyeuywewuyeu", "getMyOrders");
                }

                if (isCcontracts) {
                    getMxCcontracts(refreshType);
                } else {
                    Log.i("uwyeuywewuyeu", "getMxCcontracts");
                }
                if (isFuturesInfo) {
                    getFuturesInfo();
                } else {
                    Log.i("uwyeuywewuyeu", "getFuturesInfo");
                }

                if (isInfo) {
                    getInfo();
                } else {
                    Log.i("uwyeuywewuyeu", "getInfo");
                }


            } else {

                Log.i("kweufhwuefhiwue", "3");

            }

            handler.postDelayed(this, 4000);
        }


    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
    }


    public void setPop() {


        //2、通过Resources获取
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int heigth = dm.heightPixels;
        int width = dm.widthPixels;

        final View contentView = View.inflate(cxt, R.layout.pop_treaty_list, null);
        mPop_treaty_recy_list = (RecyclerView) contentView.findViewById(R.id.pop_treaty_recy_list);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        mPop_treaty_recy_list.setLayoutManager(linearLayoutManager);
        mPopTreatyAdapter = new PopTreatyAdapter(refreshType);
        mPop_treaty_recy_list.setAdapter(mPopTreatyAdapter);
        if (mFuturesListInfo != null) {
            List<FuturesListInfo.DataBean> data = mFuturesListInfo.getData();
            mPopTreatyAdapter.setNewData(data);
        }

        int viewHeight = Tools.getViewHeight(mPop_treaty_recy_list);

        final PopupWindow pop = new PopupWindow(contentView, width, viewHeight);
        int[] location = new int[2];
        view.getLocationInWindow(location);
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setBackgroundDrawable(cxt.getResources().getDrawable(R.color.transparent));
        pop.showAtLocation(mTrearyNameType, Gravity.CENTER | Gravity.TOP, DensityUtil.dip2px(cxt, 0), location[1] + DensityUtil.dip2px(cxt, 120));


        mPopTreatyAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                mTreatyBehaviorEdPrice.setText("");
                mTreatyBehaviorEdNumber.setText("");
                isZhang = "1";
                setBotton();
                if (mTrearyButZhang != null) {
                    mTrearyButZhang.setSelected(true);
                }

                mLeverage = null;
//                张和单位的切换
                changeType = "1";

                FuturesListInfo.DataBean dataBean = (FuturesListInfo.DataBean) adapter.getData().get(position);

                String isreverse = dataBean.getIsreverse();
                if (!"1".equals(isreverse)) {

                    mTreatyBehaviorTvNumber.setText(dataBean.getSymbol());
                } else {
                    mTreatyBehaviorTvNumber.setText(getString(R.string.zhang));
                }
                mTrearyLeverShuliangType.setText(getString(num));
                valuation = dataBean.getSettle_anchor();
                mTrearyButBtc.setText(valuation);
                refreshType = dataBean.getContract_id();
                mPair = dataBean.getPair();
                mTrearyNameType.setText(mPair + "\t" + getString(R.string.yongxu));
                setRefreshInfo(dataBean.getContract_id());
                mTreatyBehaviorTvPrice.setText(dataBean.getQuote_anchor());
//                treary_check_danwei_tv.setText("张");
                mTreatyBehaviorTvLongPrice.setText(getString(R.string.heyue_chengben) + "0.00" + "\t" + valuation);
                mTreatyBehaviorButShortPrice.setText(getString(R.string.heyue_chengben) + "0.00" + "\t" + valuation);
//                mTrearyLeverShuliangType.setText("数量(张)");
                mTrearyLeverShuliangType.setText(getString(num) + "(" + getString(R.string.zhang) + ")");

                mTreatyBehaviorTvEntrustValue.setText("0.00" + "\t" + valuation);
                pop.dismiss();

            }
        });

    }

    private void setRefreshInfo(String contract_id) {
        refreshType = contract_id;

        getMxCcontracts(refreshType);
        getMyPositions(refreshType);
//        if (isWeiTuo) {
//            getListInfo(refreshType);
//        }
        getMyOrders(refreshType);
        getInfo();

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void TreatyFragment(String event) {


        if (event.equals("Refreshs")) {

            if (getString(R.string.heyue_xianjia_shijia).equals(Config.ISLIMIT)) {

                treaty_behavior_ed_lin_price.setVisibility(View.VISIBLE);
            } else {
                treaty_behavior_ed_lin_price.setVisibility(View.GONE);
            }

            isLimit = Config.ISLIMIT;
            mTrearyCheckPriceTv.setText(Config.ISLIMIT);


        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void TreatyFragment(HeYueEventBusInfo event) {


        String name = event.name;

        refreshType = name;

        valuation = event.danwei;

        if (mTreatyBehaviorTvPrice != null) {
            mTreatyBehaviorTvPrice.setText(event.QuoteAnchor);

        }

        if (mTrearyButBtc != null) {
            mTrearyButBtc.setText(event.danwei);

        }

//        mTrearyNameType.setText();
        if (mTrearyNameType != null) {
            mTrearyNameType.setText(event.Pair + "\t" + getString(R.string.yongxu));
        }

//        treary_name_jisuan

        if (treary_name_jisuan != null) {
            treary_name_jisuan.setText("(" + event.danwei + getString(R.string.jiesuan) + ")");
        }


        if (mTreatyBehaviorTvLongPrice != null) {
            mTreatyBehaviorTvLongPrice.setText(getString(R.string.heyue_chengben) + "0.00" + "\t" + event.danwei);
        }

        if (mTreatyBehaviorButShortPrice != null) {
            mTreatyBehaviorButShortPrice.setText(getString(R.string.heyue_chengben) + "0.00" + "\t" + event.danwei);
        }

        if (mTreatyBehaviorTvEntrustValue != null) {
            mTreatyBehaviorTvEntrustValue.setText("0.00" + "\t" + event.danwei);
        }

        getMxCcontracts(refreshType);

    }


    //    获取委托价值
    public double getEntrustValue() {

        String number = mTreatyBehaviorEdNumber.getText().toString().trim();
        String price = mTreatyBehaviorEdPrice.getText().toString().trim();

        if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(price)) {

            String name = treary_check_danwei_tv.getText().toString().trim();

            if ("1".equals(isZhang)) {


                if (mIsreverse.equals("1")) {
                    double v = Double.parseDouble(number) / Double.parseDouble(price) * Double.valueOf(mContract_value);
                    return v;
                } else {
                    double v = Double.parseDouble(number) * Double.parseDouble(price) * Double.valueOf(mContract_value);
                    return v;
                }


            } else {
                Double aDouble = Double.valueOf(number);

                return aDouble;
            }


        } else {
            return 0;
        }

    }

    public void initBoolen() {
        isWeiTuo = true;
        isPositions = true;
        isOrders = true;
        isCcontracts = true;
        isFuturesInfo = true;
        isInfo = true;
    }


    Handler handlers = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    setContractorders(mTreatyPrice, mTreatyNumber, "-1");
                    break;

                case 2:
                    setContractorders(mTreatyPrice, mTreatyNumber, "1");
                    break;
                case 3:

                    getCost(String.valueOf(mTreatyPrice), String.valueOf(mTreatyNumber));

                    break;
            }
        }
    };

//

    public void setBotton() {
        mTrearyButZhang.setSelected(false);
        mTrearyButBtc.setSelected(false);
    }


    private void judge(Editable editable) {
        String temp = editable.toString();
        int posDot = temp.indexOf(".");
        //直接输入小数点的情况
        if (posDot == 0) {
            editable.insert(0, "0");
            return;
        }
        //连续输入0
        if (temp.equals("00")) {
            editable.delete(1, 2);
            return;
        }
        //输入"08" 等类似情况
        if (temp.startsWith("0") && temp.length() > 1 && (posDot == -1 || posDot > 1)) {
            editable.delete(0, 1);
            return;
        }

        //不包含小数点 不限制小数点前位数
        if (posDot < 0 && beforeDot == -1) {
            //do nothing 仅仅为了理解逻辑而已
            return;
        } else if (posDot < 0 && beforeDot != -1) {
            //不包含小数点 限制小数点前位数
            if (temp.length() <= beforeDot) {
                //do nothing 仅仅为了理解逻辑而已
            } else {
                editable.delete(beforeDot, beforeDot + 1);
            }
            return;
        }

        //如果包含小数点 限制小数点后位数
        if (temp.length() - posDot - 1 > afterDot && afterDot != -1) {
            editable.delete(posDot + afterDot + 1, posDot + afterDot + 2);//删除小数点后多余位数
        }
    }


}
